<?php

/**
 * 考场
 * @author yanghao <yh38615890@sina.cn>
 * @date 07-04-12
 * @copyright (c) gandianli
 */

namespace app\api\controller;

use app\api\Base;
use think\Config;
use think\Db;
use think\exception\HttpException;
use com\gdl\newagk\dataobject\archives\ArchivesRequestDTO;
use com\gdl\newagk\interfaces\ArchivesServiceClient;
use think\Exception;
date_default_timezone_set('PRC');//中华人民共和国时区

class AdminArchives extends Base
{
    //档案列表
    public function archivesList()
    {
        $filename['page'] = $this->request->param('page') > 1 ? $this->request->param('page/d') : 1;
        $filename['pagesize'] = $this->request->param('pagesize') > 0 ? $this->request->param('pagesize/d') : 10;
        $filename['title'] = $this->request->param('title') ? getStr($this->request->param('title'), 'string') : ''; //考生ID/真实姓名/身份证号
        $filename['plaform_id'] = $this->request->param('plaformid') ? $this->request->param('plaformid/d') : 0;
        $filename['companyid'] = $this->request->param('companyid') ? $this->request->param('companyid/d') : 0;
        $filename['exam'] = $this->request->param('exam') ? getStr($this->request->param('exam'), 'string') : ''; //考场名称/试卷名称
        $filename['examStatus'] = $this->request->param('examStatus') ? $this->request->param('examStatus/d') : 0;
        $filename['usual'] = $this->request->param('usual') ? $this->request->param('usual/d') : 0;
        $filename['pass'] = $this->request->param('eligible') ? getStr($this->request->param('eligible'), 'string') : ''; //pass 合格 nopass 不合格
        $filename['startScore'] = $this->request->param('startScore')>-1 ? sprintf("%.2f", $this->request->param('startScore')) : '';
        $filename['endScore'] = $this->request->param('endScore')>-1 ? sprintf("%.2f", $this->request->param('endScore')) : '';

        $filename['startime'] = $this->request->param('startime') ? getStr($this->request->param('startime'), 'string') : '';
        $filename['endtime'] = $this->request->param('endtime') ? getStr($this->request->param('endtime'), 'string') : '';
        $filename['terminal'] = $this->request->param('terminal') ? $this->request->param('terminal/d') : 0;
        $filename['reg'] = $this->request->param('reg') ? getStr($this->request->param('reg'), 'string') : '';

        /*         * *********** */
        if ($filename['reg'] == '') {
            $data = ['msg' => '缺少参数', 'code' => '500'];
            return json_encode($data);
        }
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk', 'gdlCloudSdk'));
            $ArchivesService = new ArchivesServiceClient(NULL);
            \ApiClient::build($ArchivesService);
            $archives = new ArchivesRequestDTO();
            $archives->filename = $filename;
            $result = $ArchivesService->archivesList($archives);

            if ($result->success == TRUE) {
                if ($result->code == 1) {
                    $plaform = ['msg' => '查询成功', 'code' => '200'];
                    $plaform['data'] = $result->data;
                    $plaform['totalNumber'] = $result->message;
                } else {
                    $plaform = ['msg' => '查询失败', 'code' => '400'];
                    $plaform['data'] = [];
                    $plaform['totalNumber'] = 0;
                }
            } else {
                $plaform = ['msg' => '没有数据', 'code' => '400'];
                $plaform['data'] = [];
                $plaform['totalNumber'] = 0;
            }
        } catch (Exception $ex) {
            $data = ['msg' => '发生异常，查询失败', 'code' => '400', 'data' => []];
        }

        return json_encode($plaform);
    }
	
	
	//下载档案列表
    public function downList()
    {
		ob_end_clean();
        $filename['title'] = $this->request->param('title') ? getStr($this->request->param('title'), 'string') : ''; //考生ID/真实姓名/身份证号
        $filename['plaform_id'] = $this->request->param('plaformid') ? $this->request->param('plaformid/d') : 0;
        $filename['companyid'] = $this->request->param('companyid') ? $this->request->param('companyid/d') : 0;
        $filename['exam'] = $this->request->param('exam') ? getStr($this->request->param('exam'), 'string') : ''; //考场名称/试卷名称
        $filename['examStatus'] = $this->request->param('examStatus') ? $this->request->param('examStatus/d') : 0;
        $filename['usual'] = $this->request->param('usual') ? $this->request->param('usual/d') : 0;
        $filename['pass'] = $this->request->param('eligible') ? getStr($this->request->param('eligible'), 'string') : ''; //pass 合格 nopass 不合格
        $filename['startScore'] = $this->request->param('startScore') ? sprintf("%.2f", $this->request->param('startScore')) : '';
        $filename['endScore'] = $this->request->param('endScore') ? sprintf("%.2f", $this->request->param('endScore')) : '';

        $filename['startime'] = $this->request->param('startime') ? getStr($this->request->param('startime'), 'string') : '';
        $filename['endtime'] = $this->request->param('endtime') ? getStr($this->request->param('endtime'), 'string') : '';
        $filename['terminal'] = $this->request->param('terminal') ? $this->request->param('terminal/d') : 0;
        $filename['reg'] = $this->request->param('reg') ? getStr($this->request->param('reg'), 'string') : '';
		$filename['down'] = 'excels';
		$filename['id'] = $this->request->param('id') ? $this->request->param('id') : '';
        /*         * *********** */
        if ($filename['reg'] == '') {
            $data = ['msg' => '缺少参数', 'code' => '500'];
            return json_encode($data);
        }
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk', 'gdlCloudSdk'));
            $ArchivesService = new ArchivesServiceClient(NULL);
            \ApiClient::build($ArchivesService);
            $archives = new ArchivesRequestDTO();
            $archives->filename = $filename;
            $result = $ArchivesService->archivesList($archives);

            if ($result->success == TRUE) {
                if ($result->code == 1) {
					$index = $result->data;
                } else {
                    $index = [];
                }
            } else {
                $index = [];
            }
        } catch (Exception $ex) {
            $index = [];
        }

        $filename = '档案列表'.date('YmdHis');  
		$header = array('姓名','性别','年龄','所属平台','所属公司','所属考场','试卷名称','开考时间','考试分数','是否异常','考试说明','考试终端');
		if(!empty($index)){
			if($error = \Excel::exportDistance($header, $index, $filename, '2007',['F'=>['w'=>20],'D'=>['w'=>25],'E'=>['w'=>20],'G'=>['w'=>30],'H'=>['w'=>20]])) {
				throw new Exception($error);
			}
		} else {
			echo " 没有数据~~~
			<script>
				function closeWindow(){ 
					window.opener=null;
					window.close();
				}
				window.setTimeout('closeWindow()',1000);
			</script>";
			
		}
    }

    //档案的查询试卷详情
    public function archivesPaper(){
		$filename['id'] = $this->request->param('id') ? $this->request->param('id/d') : 0;
		$filename['reg'] = $this->request->param('reg') ? getStr($this->request->param('reg'), 'string') : '';
		if(!$filename['id'] || $filename['reg']==''){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}
		try{
                \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
                $ArchivesService = new ArchivesServiceClient(NULL);
                \ApiClient::build($ArchivesService);
				$archives = new ArchivesRequestDTO();
				$archives->filename = $filename;
                $result = $ArchivesService->archivesPaper($archives);
				$typeScore = [1=>0,2=>0,3=>0,4=>0,5=>0,6=>0];
				
				if(empty($result->data)){
					$success=false;
				} else {
					$success=true;
					$usual = ['1'=>'正常','2'=>'考试异常','3'=>'身份异常'];
					$datas = $result->data[0];
					$types = json_decode($result->message,true);
					$questions = [];
					$datas['questions'] = unserialize($datas['questions']);
					$datas['answer'] =  unserialize($datas['answer']);
					foreach($datas['questions'] as $k=>$v){
						$questions['num'][$k] = count($v);
						foreach($v as $kv=>$vb){
							$vb['selec'] = empty($datas['answer'][$vb['id']]) ? '' : $datas['answer'][$vb['id']];
							$vb['result'] = (empty($datas['answer'][$vb['id']]) ||	$vb['answer'] !=$datas['answer'][$vb['id']]) ? 'err' : 'correct';
							
							$datas['questions'][$k][$kv]["finalAnswer"]=!empty($datas['answer'][$vb['id']]) ? $datas['answer'][$vb['id']]["answer"] : '';
							$datas['questions'][$k][$kv]["sure"] =  $datas['questions'][$k][$kv]["finalAnswer"]==$datas['questions'][$k][$kv]["answer"] ? 1 : 0;
							$typeScore[$types[$k]] += $vb['score'];
							$questions['content'][$k][] = $vb;
						}
						
					}
					$typeScore[6] = $datas['score'];
					$paper = [
							'paperName' => $datas['paperName'], //试卷名字
							'bankName' => $datas['bankName'], //题库名字
							'duration' => $datas['duration'], //考场考试时间
							'questionsNum' => $datas['questionsNum'], //有多少道题
							'passscore' => $datas['passscore'], //及格分数
							'truename' => $datas['usertruename'], //考生姓名
							'idcard' => $datas['idcard'],
							'startTime' => $datas['startTime'],
							'timeCost' => secsToStrws($datas['time']),
							'remark' => $datas['remark'],
							'usual' => $usual[$datas['usual']],//身份验证
							'score' => $datas['score'],
							'pass' => $datas['pass']==1 ? '合格' : '不合格',
							'questions' =>	$datas['questions'], // 用户做题记录/试卷
							'num' => $questions['num'], // 每道题目的数量
							'typeScore' => $typeScore, // 每道题目的数量
							];
					
				}

                if ($success == true) {
                    if ($result->code == 1) {
						$plaform = ['msg'=>'查询成功','code'=>'200'];
                        $plaform['data'] = $paper;

                    } else {
						$plaform = ['msg'=>'查询失败','code'=>'400'];
                        $plaform['data'] = [];
				
                    }
                } else {
					$plaform = ['msg'=>'没有数据','code'=>'400'];
                    $plaform['data'] = [];
			
                    
                }
        } catch (Exception $ex) {
				$data = ['msg'=>'发生异常，查询失败','code'=>'400','data'=>[]];
        }
        return json_encode($plaform);
		
	}
	
	
	//归档
    public function archivesFile(){
		$filename['id'] = $this->request->param('id') ? $this->request->param('id/d') : 0;
		$filename['reg'] = $this->request->param('reg') ? getStr($this->request->param('reg'), 'string') : '';
		if(!$filename['id'] || $filename['reg']==''){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}
		try{
                \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
                $ArchivesService = new ArchivesServiceClient(NULL);
                \ApiClient::build($ArchivesService);
				$archives = new ArchivesRequestDTO();
				$archives->filename = $filename;
                $result = $ArchivesService->archivesFile($archives);

                if ($result->success == true) {
                    if ($result->code == 1) {
						$plaform = ['msg'=>'归档成功','code'=>'200'];
                        $plaform['data'] = [];

                    } else {
						$plaform = ['msg'=>'归档失败','code'=>'400'];
                        $plaform['data'] = [];
				
                    }
                } else {
					$plaform = ['msg'=>'没有数据','code'=>'400'];
                    $plaform['data'] = [];
			
                    
                }
        } catch (Exception $ex) {
				$data = ['msg'=>'发生异常，查询失败','code'=>'400','data'=>[]];
        }
        return json_encode($plaform);
		
	}
	
	 public function archivesFileOne(){
		$filename['id'] = $this->request->param('id') ? $this->request->param('id/d') : 0;
		$filename['types'] ='ones';
		$filename['reg'] = $this->request->param('reg') ? getStr($this->request->param('reg'), 'string') : '';
		if(!$filename['id'] || $filename['reg']==''){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}
		try{
                \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
                $ArchivesService = new ArchivesServiceClient(NULL);
                \ApiClient::build($ArchivesService);
				$archives = new ArchivesRequestDTO();
				$archives->filename = $filename;
                $result = $ArchivesService->archivesFile($archives);

                if ($result->success == true) {
                    if ($result->code == 1) {
						$plaform = ['msg'=>'归档成功','code'=>'200'];
                        $plaform['data'] = [];

                    } else {
						$plaform = ['msg'=>'归档失败','code'=>'400'];
                        $plaform['data'] = [];
				
                    }
                } else {
					$plaform = ['msg'=>'没有数据','code'=>'400'];
                    $plaform['data'] = [];
			
                    
                }
        } catch (Exception $ex) {
				$data = ['msg'=>'发生异常，查询失败','code'=>'400','data'=>[]];
        }
        return json_encode($plaform);
		
	}


}
